//
//  ListViewController.m
//  CarLifes
//
//  Created by yu on 2017/6/14.
//  Copyright © 2017年 jpas. All rights reserved.
//

#import "ListViewController.h"
#import "ListCell.h"
#import "EquipmentModel.h"

#import "SearchTraceViewController.h"
#import "TracingViewController.h"
#import "UserInfoViewController.h"
#import "RoutePlanViewController.h"
#import "AlarmViewController.h"
#import "DepartmentModel.h"
#import "TreeView.h"
#import "KLCPopup.h"

#define kReuseIdentifier @"ListCellIdentifier"

@interface ListViewController ()<UITableViewDelegate,UITableViewDataSource,DZNEmptyDataSetSource,
DZNEmptyDataSetDelegate,UITextFieldDelegate>

{
    BOOL _isOpen;
    NSIndexPath *_selectIndex;
}

@property (strong, nonatomic) IBOutlet UIView *btnView;
@property (weak, nonatomic) IBOutlet UIView *containerView;
@property (nonatomic, strong) UIButton *select;
@property (strong, nonatomic) IBOutletCollection(UIButton) NSArray *btns;
@property (weak, nonatomic) IBOutlet UIView *lineView;
@property (weak, nonatomic) IBOutlet UIView *lineBgView;

/////
@property (weak, nonatomic) IBOutlet UITableView *tableView;
@property (nonatomic, strong) NSMutableArray *dataSource;
@property (nonatomic, copy) NSString *status;
@property (nonatomic, copy) NSString *actStatus;
@property (nonatomic, assign) NSInteger page;

@property (nonatomic, strong) NSArray *depts;
@property (nonatomic, strong) NSMutableArray *deptArray;
@property (nonatomic, strong) UIButton *titleBtn;

@property (nonatomic, strong) KLCPopup *popup;

@property (nonatomic, strong) TreeView *treeView;
@property (nonatomic, strong) DepartmentModel *dModel;

@end

@implementation ListViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.page = 1;
    _isOpen = YES;
    
    [self.tableView registerNib:NIB_NAMED(kReuseIdentifier) forCellReuseIdentifier:kReuseIdentifier];
    
    MJRefreshNormalHeader *header = [MJRefreshNormalHeader headerWithRefreshingTarget:self refreshingAction:@selector(loadNewEquipsData)];
    header.lastUpdatedTimeLabel.hidden = YES;
    self.tableView.mj_header = header;
    
    self.tableView.mj_footer = [MJRefreshBackNormalFooter footerWithRefreshingTarget:self refreshingAction:@selector(loadMoreData)];
    
    [self setupNaviUI];
    [self setupPopupView];
    [self loadDepts];
    [self loadNewEquipsData];
}

- (void)loadDepts {
    self.deptArray = [NSMutableArray array];
    DeptModel *dModel = [User sharedUser].deptModel;
    [self.requestTool findDeptsByDeptId:dModel.deptId success:^(NSArray *depts) {
        self.depts = depts;
        // 法1
        [self checkChildWithPId:dModel.parentDeptId level:0];
        // 法2
        //[self treeList:[user.deptModel.parentDeptId integerValue] level:0 list:depts];
    } failure:^(NSString *error) {
        
    }];
}

- (void)treeList:(NSInteger)parentId level:(NSInteger)level list:(NSArray *)list {

    int i = 0;
    for (DepartmentModel *dm in list) {
        NSInteger did = [dm.deptId integerValue];
        NSInteger pid = [dm.parentDeptId integerValue];
        int k = 0;
        if (parentId == pid) {k++;}
        
        if (k != 0) {
            DepartmentModel *dep = list[i];
            dep.level = level + 1;
            [self.deptArray addObject:dep];
            [self treeList:did level:level + 1 list:list];
        }
        i++;
    }
}

- (void)checkChildWithPId:(NSString *)pId level:(NSInteger)level {
    NSPredicate *predicate = [NSPredicate predicateWithFormat:@"parentDeptId = %@",pId];
    NSArray *result = [self.depts filteredArrayUsingPredicate:predicate];
    for (DepartmentModel *dModel in result) {
        dModel.level = level + 1;
        [self.deptArray addObject:dModel];
        [self checkChildWithPId:dModel.deptId level:level + 1];
    }
}

- (void)setupNaviUI
{
    CGFloat titleViewHeight = 40.;
    CGFloat titleViewWidth = kScreenWidth * 0.95;
    
    UIView *titleView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, titleViewWidth, titleViewHeight)];
    
    CGFloat titleBtnHeight = 38.;
    CGFloat titleBtnWidth = titleViewWidth * 0.7;
    CGFloat titleBtnX = (titleViewWidth - titleBtnWidth) / 2;
    CGFloat titleBtnY = (titleViewHeight - titleBtnHeight) / 2;
    
    self.titleBtn = [[UIButton alloc] initWithFrame:CGRectMake(titleBtnX, titleBtnY, titleBtnWidth, titleBtnHeight)];
    [self.titleBtn setTitle:[User sharedUser].deptName forState:UIControlStateNormal];
    [self.titleBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    [self.titleBtn setImage:IMAGE_NAMED(@"down_arrow") forState:UIControlStateNormal];
    [self.titleBtn setSemanticContentAttribute:UISemanticContentAttributeForceRightToLeft];
    [self.titleBtn setImageEdgeInsets:UIEdgeInsetsMake(0, 5, 0, 0)];
    [self.titleBtn setAdjustsImageWhenHighlighted:NO];
    [self.titleBtn addTarget:self action:@selector(transferAccountAction) forControlEvents:UIControlEventTouchUpInside];
    
    [titleView addSubview:self.titleBtn];
    self.navigationItem.titleView = titleView;
}

- (void)setupPopupView
{
    self.treeView = [[TreeView alloc] initWithFrame:CGRectMake(0, 0, kScreenWidth, kScreenWidth)];
    
//    self.treeView = [TreeView customerView];
//    self.treeView.frame = CGRectMake(0, 0, kScreenWidth, kScreenWidth);
    self.treeView.deptArray = self.deptArray;
    
    @weakify(self);
    [self.treeView setCancelBlock:^{
        @strongify(self);
        [self.popup dismiss:YES];
    }];
    
    [self.treeView setConfirmBlock:^(DepartmentModel * _Nonnull dModel) {
        @strongify(self);
        [self.popup dismiss:YES];
        [[User sharedUser].deptModel setChildDeptId:dModel.deptId];
        [self.titleBtn setTitle:dModel.deptName forState:UIControlStateNormal];
        
        self.dModel = dModel;
        [self loadNewEquipsData];
    }];
    
    if (self.popup == nil) {
        self.popup = [KLCPopup popupWithContentView:self.treeView
                                           showType:KLCPopupShowTypeSlideInFromBottom
                                        dismissType:KLCPopupDismissTypeSlideOutToBottom
                                           maskType:KLCPopupMaskTypeDimmed
                           dismissOnBackgroundTouch:YES
                              dismissOnContentTouch:NO];
    }
}

// 切换账户点击事件
- (void)transferAccountAction {
    [self.treeView updateSelectStatus];
    self.treeView.deptArray = self.deptArray;

    [self.popup showWithLayout:KLCPopupLayoutMake(KLCPopupHorizontalLayoutCenter, KLCPopupVerticalLayoutBottom)];
}

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    [UIApplication sharedApplication].statusBarStyle = UIStatusBarStyleLightContent;
}

/** 请求更多设备数据*/
- (void)loadMoreData
{
    if (![PPNetworkHelper isNetwork]) {
        [self.tableView.mj_footer endRefreshing];
        [MBProgressHUD showToast:@"网络已断开,请检查网络设置"];
        return;
    }
   
    NSString *deptId = self.dModel.deptId ? : [User sharedUser].deptModel.childDeptId;
    self.page++;
    [self.requestTool loadEquipsByPage:self.page size:10 status:self.status actStatus:self.actStatus str:@"" deptId:deptId show:YES success:^(NSArray *equips, NSArray *equipCounts) {
        [self.dataSource addObjectsFromArray:equips];
        [self.tableView reloadData];
        
        if (equips.count < 10) {
            [self.tableView.mj_footer endRefreshingWithNoMoreData];
        } else {
            [self.tableView.mj_footer endRefreshing];
        }
        if (!equips.count) {
            self.tableView.emptyDataSetDelegate = self;
            self.tableView.emptyDataSetSource = self;
        }
    } failure:^(NSString *error) {
        [self.tableView.mj_footer endRefreshing];
        PPLog(@"load equips error = %@",error);

    }];
}

- (void)setContainerView:(UIView *)containerView {
    _containerView = containerView;
    [containerView addSubview:_btnView];
    _btnView.sd_layout.spaceToSuperView(UIEdgeInsetsZero);
}

- (void)setTableView:(UITableView *)tableView
{
    _tableView = tableView;
    if (@available(iOS 13.0, *)) {
        UIColor *bgColor = [UIColor colorWithDynamicProvider:^UIColor * _Nonnull(UITraitCollection * _Nonnull traitCollection) {
            if (traitCollection.userInterfaceStyle == UIUserInterfaceStyleLight) {
                return kBackGroundLightGrayColor;
            } else {
                return UIColor.systemBackgroundColor;
            }
        }];
        _tableView.backgroundColor = bgColor;
    } else {
        _tableView.backgroundColor = kBackGroundLightGrayColor;
    }
}

- (void)setBtns:(NSArray *)btns {
    _btns = btns;
    for (UIButton *btn in btns) {
        //btn.titleLabel.font = [UIFont boldSystemFontOfSize:15];
        if (@available(iOS 13.0, *)) {
            UIColor *btnColor = [UIColor colorWithDynamicProvider:^UIColor * _Nonnull(UITraitCollection * _Nonnull traitCollection) {
                if (traitCollection.userInterfaceStyle == UIUserInterfaceStyleLight) {
                    return UIColor.blackColor;
                } else {
                    return UIColor.secondaryLabelColor;
                }
            }];
            [btn setTitleColor:btnColor forState:UIControlStateNormal];
        } else {
            [btn setTitleColor:UIColor.blackColor forState:UIControlStateNormal];
        }
        [btn setTitleColor:kBaseColor forState:UIControlStateSelected];
        if (btn.tag == 1) {
            btn.selected = YES;
            self.select = btn;
        }
    }
}

- (void)loadNewEquipsData {
    if (![PPNetworkHelper isNetwork]) {
        [self.tableView.mj_header endRefreshing];
        [MBProgressHUD showToast:@"网络已断开,请检查网络设置"];
        return;
    }
    self.page = 1;

    NSString *deptId = self.dModel.deptId ? : [User sharedUser].deptModel.childDeptId;
    
    [self.requestTool loadEquipsByPage:self.page size:10 status:self.status actStatus:self.actStatus str:@"" deptId:deptId show:YES success:^(NSArray *equips, NSArray *equipCounts) {
        self.dataSource = [NSMutableArray arrayWithArray:equips];
        [self updateBtnTitle:equipCounts];
        [self.tableView reloadData];
        [self.tableView.mj_header endRefreshing];
        [self.tableView.mj_footer resetNoMoreData];
    } failure:^(NSString *error) {
        [self.tableView.mj_header endRefreshing];
        PPLog(@"load equips error = %@",error);
    }];
}

- (void)updateBtnTitle:(NSArray *)equipCounts
{
    EquipStatusCount *equipCount = equipCounts.firstObject;
    [self.btns[0] setTitle:NSStringFormat(@"全部(%@)",equipCount.total?:@"0") forState:UIControlStateNormal];
    [self.btns[1] setTitle:NSStringFormat(@"在线(%@)",equipCount.ol?:@"0") forState:UIControlStateNormal];
    [self.btns[2] setTitle:NSStringFormat(@"离线(%@)",equipCount.off?:@"0") forState:UIControlStateNormal];
    [self.btns[3] setTitle:NSStringFormat(@"未启用(%@)",equipCount.unact?:@"0") forState:UIControlStateNormal];
}

- (IBAction)btnsClick:(id)sender {
    UIButton *btn = (UIButton *)sender;
    [self settingBtn:btn];
    self.page = 1;
    
    switch (btn.tag)
    {
        // 全部
        case 1:self.status = @"";self.actStatus = @""; break;
        // 在线
        case 2:self.status = @"0,1";self.actStatus = @""; break;
        // 离线
        case 3:self.status = @"2";self.actStatus = @""; break;
        // 未激活
        case 4:self.status = @"3";self.actStatus = @"0"; break;
            
        default:break;
    }
    
    _selectIndex = nil;
    _isOpen = YES;
    [self loadNewEquipsData];
}

- (void)settingBtn:(UIButton *)btn {
    if (btn != self.select) {
        self.select.selected = NO;
        btn.selected = YES;
        self.select = btn;
    } else {
        self.select.selected = YES;
    }
    
    [UIView animateWithDuration:0.25f animations:^{
        _lineView.centerX_sd = (kScreenWidth/8)*(2*btn.tag-1);
        [self.tableView setContentOffset:CGPointZero animated:NO];
    }];
}

#pragma mark - UITableViewDelegate,UITableViewDataSource -

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return self.dataSource.count;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    if (_selectIndex != nil && _selectIndex.section == section) {
        if (_isOpen) {
            return 2;
        } else {
            return 1;
        }
    } else {
        return 1;
    }
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.row) {
        return 66;
    } else {
        return 80;
    }
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    ListCell *cell = [ListCell initTableViewCellWith:tableView indexPath:indexPath];
    EquipmentModel *model = self.dataSource[indexPath.section];
    [cell setModel:model];
    
#pragma mark - antion -
    [cell setFuncActionBlock:^(NSInteger index) {
        switch (index) {
            case 0:
            {//轨迹回放
                SearchTraceViewController *ct = [[SearchTraceViewController alloc] init];
                ct.eqNo = model.eqNo;
                ct.ownerName = model.ownerName;
                [self.navigationController pushViewController:ct animated:YES];
            }
                break;
            case 1:
            {//实时跟踪
                if ([model.pointModel.lat isKindOfClass:[NSNull class]] || [model.pointModel.lng isKindOfClass:[NSNull class]]) {
                    [[[UIAlertView alloc] initWithTitle:@"该设备未定位" message:nil delegate:nil cancelButtonTitle:@"确定" otherButtonTitles:nil, nil] show];
                    return;
                }
                TracingViewController *tracing = [[TracingViewController alloc] init];
                tracing.eqNo = model.eqNo;
                tracing.ownerName = model.ownerName;
                [self.navigationController pushViewController:tracing animated:YES];
            }
                break;
            case 2:
            {//用户信息
                UserInfoViewController *userInfo = [[UserInfoViewController alloc] init];
                userInfo.eqNo = model.eqNo;
                [self.navigationController pushViewController:userInfo animated:YES];
            }
                break;
            case 3:
            {//一键追车
                if ([model.pointModel.lat isKindOfClass:[NSNull class]] || [model.pointModel.lng isKindOfClass:[NSNull class]]) {
                    [[[UIAlertView alloc] initWithTitle:@"该设备未定位" message:nil delegate:nil cancelButtonTitle:@"确定" otherButtonTitles:nil, nil] show];
                    return;
                }
                RoutePlanViewController *navigation = [[RoutePlanViewController alloc] init];
                navigation.destinationPoint = [[CLLocation alloc] initWithLatitude:[model.pointModel.lat doubleValue] longitude:[model.pointModel.lng doubleValue]];
                [self.navigationController
                 pushViewController:navigation animated:YES];
            }
                break;
            case 4:
            {//设备报警
                AlarmViewController *alarm = [[AlarmViewController alloc] init];
                alarm.eqNo = model.eqNo;
                alarm.ownerName = model.ownerName;
                alarm.egId = model.egId;
                [self.navigationController pushViewController:alarm animated:YES];
            }
                break;
            default:
                break;
        }
    }];
    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    EquipmentModel *eModel = self.dataSource[indexPath.section];
    if ([eModel.status isEqualToString:@"3"] ) {
        [[[UIAlertView alloc] initWithTitle:@"该设备未定位" message:nil delegate:nil cancelButtonTitle:@"确定" otherButtonTitles:nil, nil] show];
        return;
    }
    
    if ([eModel.mark isEqualToString:@"D"]) {
        [[[UIAlertView alloc] initWithTitle:@"该设备已被禁用" message:nil delegate:nil cancelButtonTitle:@"确定" otherButtonTitles:nil, nil] show];
        return;
    }

    NSMutableIndexSet *indexSet = [[NSMutableIndexSet alloc] initWithIndex:indexPath.section];
        if (_selectIndex != nil && indexPath.section == _selectIndex.section) {
            _isOpen = !_isOpen;
        } else if (_selectIndex != nil && indexPath.section != _selectIndex.section) {
            indexSet = [[NSMutableIndexSet alloc] initWithIndex:indexPath.section];
            [indexSet addIndex:_selectIndex.section];
            _isOpen = YES;
        }
    _selectIndex = indexPath;
    [tableView reloadSections:indexSet withRowAnimation:UITableViewRowAnimationFade];
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
    return 0.001;
}

- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section {
    return 0.001;
}

- (NSAttributedString *)titleForEmptyDataSet:(UIScrollView *)scrollView {
    NSString *title = @"暂无相关数据";
    NSDictionary *attributes = @{NSFontAttributeName:[UIFont boldSystemFontOfSize:16.0f],NSForegroundColorAttributeName:[UIColor darkGrayColor]};
    return [[NSAttributedString alloc] initWithString:title attributes:attributes];
}

- (BOOL)emptyDataSetShouldAllowScroll:(UIScrollView*)scrollView {
    return YES;
}

- (NSString *)status
{
    if (_status == nil) {
        _status = @"";
    }
    return _status;
}

- (NSString *)actStatus
{
    if (_actStatus == nil) {
        _actStatus = @"";
    }
    return _actStatus;
}

@end
